<?php
session_start();
header('Content-Type: application/json');

// 用户数据（实际应从数据库或安全存储读取，这里直接写死）
$users = [
  ["username" => "tanbaolong", "password" => "700704181..Tan"]
];

$action = $_GET['action'] ?? '';

if ($action === 'login') {
  $input = json_decode(file_get_contents('php://input'), true);
  $u = $input['username'] ?? '';
  $p = $input['password'] ?? '';
  $ok = false;
  foreach ($users as $user) {
    if ($user['username'] === $u && $user['password'] === $p) {
      $_SESSION['admin'] = $u;
      $ok = true;
      break;
    }
  }
  if ($ok) {
    echo json_encode(['success'=>true]);
  } else {
    echo json_encode(['success'=>false, 'msg'=>'用户名或密码错误']);
  }
  exit;
}

if ($action === 'logout') {
  unset($_SESSION['admin']);
  echo json_encode(['success'=>true]);
  exit;
}

if (!isset($_SESSION['admin'])) {
  echo json_encode(['success'=>false, 'msg'=>'未登录']);
  exit;
}

if ($action === 'get') {
  $cfg = json_decode(file_get_contents('config.json'), true);
  echo json_encode($cfg);
  exit;
}
if ($action === 'save') {
  $input = json_decode(file_get_contents('php://input'), true);
  $cfg = json_decode(file_get_contents('config.json'), true);
  $cfg['siteTitle'] = $input['siteTitle'] ?? $cfg['siteTitle'];
  $cfg['apiPlatform'] = $input['apiPlatform'] ?? $cfg['apiPlatform'];
  $cfg['amapKey'] = $input['amapKey'] ?? $cfg['amapKey'];
  $cfg['qweatherKey'] = $input['qweatherKey'] ?? $cfg['qweatherKey'];
  $cfg['qweatherHost'] = $input['qweatherHost'] ?? $cfg['qweatherHost'];
  $cfg['qweatherJwt'] = $input['qweatherJwt'] ?? $cfg['qweatherJwt'];
  $cfg['aliyunAppCode'] = $input['aliyunAppCode'] ?? $cfg['aliyunAppCode'];
  file_put_contents('config.json', json_encode($cfg, JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT));
  echo json_encode(['success'=>true]);
  exit;
}

echo json_encode(['success'=>false, 'msg'=>'未知操作']); 